package com.thesis.client;

import java.util.Calendar;

import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.NumericWheelAdapter;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.thesis.conectify.Connectify;
import com.thesis.object.Date;
import com.thesis.object.ListBill;
import com.thesis.utils.Utils;

public class RevenueActivity extends Activity {

	Calendar cal = Calendar.getInstance();

	int yy = cal.get(Calendar.YEAR);
	int mm = cal.get(Calendar.MONTH);
	int dd = cal.get(Calendar.DAY_OF_MONTH);
	ListBill listBill;
	EditText tv_dayfrom;
	EditText tv_dayto;
	Date dateBegin;
	Date dateEnd;

	TextView tv_revenune;
	TextView tv_turn ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_revenue);
		
		
		tv_dayfrom = (EditText) findViewById(R.id.re_et_dayfrom);
		tv_dayto = (EditText) findViewById(R.id.re_et_dayto);
		tv_revenune = (TextView) findViewById(R.id.re_tv_revenue);
		tv_turn = (TextView) findViewById(R.id.re_tv_viewturn);
		
		ImageButton btn_dayfrom = (ImageButton) findViewById(R.id.re_ib_dayfrom);
		ImageButton btn_dayto = (ImageButton) findViewById(R.id.re_ib_dayto);
		Button btn_view_revenue = (Button) findViewById(R.id.re_b_revenue);
		btn_view_revenue.setBackground(getResources().getDrawable(
				R.drawable.button_view));

		tv_dayfrom.setText((new StringBuilder()
				// Month is 0 based, just add 1
				.append(dd).append("-").append(mm + 1).append("-")
				.append(yy)).toString());
		tv_dayto.setText((new StringBuilder()
				// Month is 0 based, just add 1
				.append(dd).append("-").append(mm + 1).append("-")
				.append(yy)).toString());

		btn_dayfrom.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				TimepickFrom(RevenueActivity.this);
				
			}
		});

		btn_dayto.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				TimepickTo(RevenueActivity.this);
				
			}
		});

		btn_view_revenue.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (isValid(dateBegin, dateEnd)){
					new ViewRevenue().execute();
				}else{
					Utils.sharedInstance().showShortToast(RevenueActivity.this, 
							getResources().getString(R.string.err_date));
				}
				
			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.revenue, menu);
		return true;
	}

	private void TimepickFrom(final Context cons) {
		LayoutInflater inf = LayoutInflater.from(cons);
		// layout of alert box contains
		View view = inf.inflate(R.layout.wheeldate, null);

		// minute wheel
		final WheelView month = (WheelView) view.findViewById(R.id.month);
		month.setViewAdapter(new NumericWheelAdapter(cons, 1, 12));
		month.setCyclic(false);

		final WheelView year = (WheelView) view.findViewById(R.id.year);
		year.setViewAdapter(new NumericWheelAdapter(cons, yy - 5, yy + 5));
		year.setCyclic(false);

		final WheelView date = (WheelView) view.findViewById(R.id.date);
		date.setViewAdapter(new NumericWheelAdapter(cons, 1, 31));
		date.setCyclic(false);

		OnWheelChangedListener changelistener_month = new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				date.setViewAdapter(new NumericWheelAdapter(
						cons,
						1,
						dayOfmonth(newValue + 1, year.getCurrentItem() - 5 + yy)));
			}
		};
		OnWheelChangedListener changelistener_year = new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				date.setViewAdapter(new NumericWheelAdapter(
						cons,
						1,
						dayOfmonth(month.getCurrentItem() + 1, newValue - 5 + yy)));
			}
		};

		date.setCurrentItem(dd - 1);
		month.setCurrentItem(mm);
		year.setCurrentItem(5);

		month.addChangingListener(changelistener_month);
		year.addChangingListener(changelistener_year);

		new AlertDialog.Builder(cons)
				.setMessage("Chon ngày")
				.setView(view)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						// write code of lines, whatever want to with
						// value of this timepicker
						// hour value= hours.getCurrentItem();
						// minute value = mins.getCurrentItem();

						tv_dayfrom.setText((new StringBuilder()
								// Month is 0 based, just add 1
								.append(date.getCurrentItem() + 1)
								.append("-").append(month.getCurrentItem() + 1)
								.append("-")
								.append(year.getCurrentItem() - 5 + yy)).toString());
						dateBegin  = new Date(date.getCurrentItem() + 1,
								month.getCurrentItem() + 1, year.getCurrentItem() - 5 + yy);
						Log.d("daybegin      ",dateBegin.getStringdate());
						
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								return;
							}
						}).create().show();

		// set time

	}

	private void TimepickTo(final Context cons) {
		LayoutInflater inf = LayoutInflater.from(cons);
		// layout of alert box contains
		View view = inf.inflate(R.layout.wheeldate, null);

		// minute wheel
		final WheelView month = (WheelView) view.findViewById(R.id.month);
		month.setViewAdapter(new NumericWheelAdapter(cons, 1, 12));
		month.setCyclic(false);

		final WheelView year = (WheelView) view.findViewById(R.id.year);
		year.setViewAdapter(new NumericWheelAdapter(cons, yy - 5, yy + 5));
		year.setCyclic(false);

		final WheelView date = (WheelView) view.findViewById(R.id.date);
		date.setViewAdapter(new NumericWheelAdapter(cons, 1, dayOfmonth(
				month.getCurrentItem() + 1, year.getCurrentItem() - 5 + yy)));
		date.setCyclic(false);

		OnWheelChangedListener changelistener_month = new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				date.setViewAdapter(new NumericWheelAdapter(
						cons,
						1,
						dayOfmonth(newValue + 1, year.getCurrentItem() - 5 + yy)));
			}
		};
		OnWheelChangedListener changelistener_year = new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				date.setViewAdapter(new NumericWheelAdapter(
						cons,
						1,
						dayOfmonth(month.getCurrentItem() + 1, newValue - 5 + yy)));
			}
		};

		date.setCurrentItem(dd - 1);
		month.setCurrentItem(mm);
		year.setCurrentItem(5);

		month.addChangingListener(changelistener_month);
		year.addChangingListener(changelistener_year);

		new AlertDialog.Builder(cons)
				.setMessage("Chọn ngày")
				.setView(view)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						// write code of lines, whatever want to with
						// value of this timepicker
						// hour value= hours.getCurrentItem();
						// minute value = mins.getCurrentItem();

						tv_dayto.setText((new StringBuilder()
								// Month is 0 based, just add 1
								.append(date.getCurrentItem() + 1)
								.append("-").append(month.getCurrentItem() + 1)
								.append("-")
								.append(year.getCurrentItem() - 5 + yy)).toString());
						dateEnd  = new Date(date.getCurrentItem() + 1,
								month.getCurrentItem() + 1, year.getCurrentItem() - 5 + yy);
						Log.d("dayend     ",dateEnd.getStringdate());
						
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								return;
							}
						}).create().show();

		// set time

	}

	private int dayOfmonth(int month, int year) {
		if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8
				|| month == 10 || month == 12)
			return 31;
		else if (month == 4 || month == 6 || month == 9 || month == 11)
			return 30;
		else if (month == 2 && ((year % 4 == 0) && (year % 100 != 0))
				|| (year % 400 == 0))
			return 29;
		else
			return 28;
	}

	private boolean isValid (Date begin , Date end){
		if ( begin.getYear() <= end.getYear()) return true;
		else {
			if (begin.getMonth() <= end.getMonth()) return true;
			else { 
				if (begin.getDay() <= end.getDay()) return true;
				else return false;
			}
		}
		
	}
	
	public class ViewRevenue extends AsyncTask<String, String, String>{

		@Override
		protected String doInBackground(String... params) {
			
			Connectify connect = new Connectify(RevenueActivity.this);
			//Log.d ("TESTTTTTTTTTT","" +8+dateBegin.getStringdate()+"   "+ dateEnd.getStringdate());
			listBill = connect.getListBill(dateBegin.getStringdate(), dateEnd.getStringdate());
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			int cost = 0 ;
		
			for (int i = 0  ; i < listBill.getListBill().size();i++){
				cost += listBill.getListBill().get(i).getTotalCost();
			}
			tv_revenune.setText(""+cost+" đồng");

			tv_turn.setText(""+listBill.getListBill().size()+" lượt");
			
		}
	}
}
